package com.hcc.flow.server.advice;

import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hcc.flow.server.annotation.LogAnnotation;
import com.hcc.flow.server.common.utils.StringUtilsV2;
import com.hcc.flow.server.dto.sys.VerifyDto;
import com.hcc.flow.server.model.sys.SysAuditLogs;
import com.hcc.flow.server.model.sys.SysLogs;
import com.hcc.flow.server.service.sys.SysLogService;
import com.hcc.flow.server.utils.UserUtil;

import io.swagger.annotations.ApiOperation;

/**
 * 统一日志处理
 *
 * @author 韩长长 
 *
 * 
 */
@Aspect
@Component
public class LogAdvice {

	@Autowired
	private SysLogService logService;

	// 环绕通知日志保存
	@Around(value = "@annotation(com.hcc.flow.server.annotation.LogAnnotation)")
	public Object logSave(ProceedingJoinPoint joinPoint) throws Throwable {
		SysLogs sysLogs = new SysLogs();
		String userId = UserUtil.getLoginUser().getUserId();
		sysLogs.setUserId(userId);
		MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
		Integer code = null;
		LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
		String module = logAnnotation.module();
		if (StringUtilsV2.isEmpty(module)) {
			ApiOperation apiOperation = methodSignature.getMethod().getDeclaredAnnotation(ApiOperation.class);
			if (apiOperation != null) {
				module = apiOperation.value();
				code = apiOperation.code();
			}
		}

		if (StringUtilsV2.isEmpty(module)) {
			throw new RuntimeException("没有指定日志module");
		}
		sysLogs.setModule(module);

		try {
			if (code != null && !code.equals(200)){
				String id = null;
				Object object = joinPoint.getArgs()[0];
				
				if (code % 2 == 0) {
					id = (String) (object);
					logService.saveAuditLogs(new SysAuditLogs(userId, new Date(),module, id));
				} else if (code % 2 == 1) {
					id = ((VerifyDto) object).getId();
					String rejectReason = ((VerifyDto) object).getRejectReason();
					if(StringUtilsV2.isBlank(rejectReason)){
						
					}
					logService.saveAuditLogs(new SysAuditLogs(userId, new Date(),module + "<br/>驳回原因：" + rejectReason, id));
				}

			}
			Object object = joinPoint.proceed();
			sysLogs.setFlag(true);
			sysLogs.setLogType(1);
			return object;
		} catch (Exception e) {
			sysLogs.setFlag(false);
			sysLogs.setRemark(e.getMessage());
			throw e;
		} finally {
			if (sysLogs.getUserId() != null) {
				logService.save(sysLogs);
			}
		}
	}
}
